﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using BartonExtension;
using System.Web.Script.Services;
using ResponseObject;
using SqlServerWrapper;
using System.Data.SqlClient;
using System.Data;
using Model;

namespace WebSrvs.NET
{
    /// <summary>
    /// ZK_BackEndService 的摘要说明
    /// </summary>
    [System.Web.Script.Services.ScriptService]
    [WebService(Namespace = "http://zker.hk/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消注释以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class ZK_BackEndService : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string delete_store(int store_id)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_delete_store";
                    cmd.Parameters.Add("@store_id", SqlDbType.Int).Value = store_id;
                    cmd.Parameters.Add("@return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                    try
                    {
                        cmd.ExecuteNonQuery();
                        int returnVal = cmd.Parameters["@return"].Value.toInt32().Value;
                        if (returnVal == -1)
                        {
                            response.isProcessSuccess = false;
                            response.errCode = ErrorCodes.CODE_ERR_ON_DELETE_STORE_FAIL;
                            response.errMsg = ErrorMsgs.MSG_ERR_ON_DELETE_STORE_FAIL;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string AddStore(int store_type, string title, float frequency, string brands,
                               string in_brand_catalogs, string catalogs, string in_catalog_brands, string in_brand_low_price,
                               string in_brand_top_price, string in_brand_low_discount, string in_brand_top_discount,
                               string region, string plaza_title, float plaza_geolocation_lat, float plaza_geolocation_lon,
                               string in_plaza_location, string street_detail, string activity_detail, string sale_rate,
                               string launch_time, string end_time)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_add_store";
                    cmd.Parameters.Add("@store_type", SqlDbType.Int).Value = store_type;
                    cmd.Parameters.Add("@title", SqlDbType.VarChar).Value = title;
                    cmd.Parameters.Add("@frequency", SqlDbType.Float).Value = frequency;
                    cmd.Parameters.Add("@brands", SqlDbType.VarChar).Value = brands;
                    cmd.Parameters.Add("@in_brand_catalogs", SqlDbType.VarChar).Value = in_brand_catalogs;
                    cmd.Parameters.Add("@catalogs", SqlDbType.VarChar).Value = catalogs;
                    cmd.Parameters.Add("@in_catalog_brands", SqlDbType.VarChar).Value = in_catalog_brands;
                    cmd.Parameters.Add("@in_brand_low_price", SqlDbType.NVarChar).Value = in_brand_low_price;
                    cmd.Parameters.Add("@in_brand_top_price", SqlDbType.NVarChar).Value = in_brand_top_price;
                    cmd.Parameters.Add("@in_brand_low_discount", SqlDbType.NVarChar).Value = in_brand_low_discount;
                    cmd.Parameters.Add("@in_brand_top_discount", SqlDbType.NVarChar).Value = in_brand_top_discount;
                    cmd.Parameters.Add("@region", SqlDbType.VarChar).Value = region;
                    cmd.Parameters.Add("@plaza_title", SqlDbType.VarChar).Value = plaza_title;
                    cmd.Parameters.Add("@plaza_geolocation_lat", SqlDbType.Float).Value = plaza_geolocation_lat;
                    cmd.Parameters.Add("@plaza_geolocation_lon", SqlDbType.Float).Value = plaza_geolocation_lon;
                    cmd.Parameters.Add("@in_plaza_location", SqlDbType.VarChar).Value = in_plaza_location;
                    cmd.Parameters.Add("@street_detail", SqlDbType.VarChar).Value = street_detail;
                    cmd.Parameters.Add("@activity_detail", SqlDbType.VarChar).Value = string.IsNullOrEmpty(activity_detail) ? (object)DBNull.Value : activity_detail;
                    cmd.Parameters.Add("@sale_rate", SqlDbType.NVarChar).Value = string.IsNullOrEmpty(sale_rate) ? (object)DBNull.Value : sale_rate;
                    cmd.Parameters.Add("@launch_time", SqlDbType.NVarChar).Value = string.IsNullOrEmpty(launch_time) ? (object)DBNull.Value : launch_time;
                    cmd.Parameters.Add("@end_time", SqlDbType.NVarChar).Value = string.IsNullOrEmpty(end_time) ? (object)DBNull.Value : end_time;
                    cmd.Parameters.Add("@return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                    try
                    {
                        cmd.ExecuteNonQuery();
                        int returnVal = cmd.Parameters["@return"].Value.toInt32().Value;
                        if (returnVal != 0)
                        {
                            response.isProcessSuccess = false;
                            response.errCode = ErrorCodes.CODE_ERR_ON_BACKEND_ADD_STORE;
                            response.errMsg = ErrorMsgs.MSG_ERR_ON_BACKEND_ADD_STORE;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string LocationAvailabilityCheck(string region, string plaza_title, string in_plaza_location)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_check_availability_on_location";
                    cmd.Parameters.Add("@region", SqlDbType.VarChar).Value = region;
                    cmd.Parameters.Add("@plaza_title", SqlDbType.VarChar).Value = plaza_title;
                    cmd.Parameters.Add("@in_plaza_location", SqlDbType.VarChar).Value = in_plaza_location;
                    cmd.Parameters.Add("@return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                    try
                    {
                        cmd.ExecuteNonQuery();
                        int returnVal = cmd.Parameters["@return"].Value.toInt32().Value;
                        if (returnVal > 0)
                        {
                            response.isProcessSuccess = false;
                            response.errCode = ErrorCodes.CODE_ERR_ON_BACKEND_LOCATION_EXIST;
                            response.errMsg = ErrorMsgs.MSG_ERR_ON_BACKEND_LOCATION_EXIST;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string ActivityInStoreExists(int store_id, string activity_detail, string activity_launch_time, string activity_end_time)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_check_availability_on_activity";
                    cmd.Parameters.Add("@store_id", SqlDbType.Int).Value = store_id;
                    cmd.Parameters.Add("@activity_detail", SqlDbType.VarChar).Value = activity_detail;
                    cmd.Parameters.Add("@launch_time", SqlDbType.DateTime).Value = DateTime.Parse(activity_launch_time);
                    cmd.Parameters.Add("@end_time", SqlDbType.DateTime).Value = DateTime.Parse(activity_end_time);
                    cmd.Parameters.Add("@return",SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                    try
                    {
                        cmd.ExecuteNonQuery();
                        int returnVal = cmd.Parameters["@return"].Value.toInt32().Value;
                        if (returnVal > 0)
                        {
                            response.isProcessSuccess = false;
                            response.errCode = ErrorCodes.CODE_ERR_ON_BACKEND_ACTIVITY_EXISTS;
                            response.errMsg = ErrorMsgs.MSG_ERR_ON_BACKEND_ACTIVITY_EXISTS;
                        }
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string BatchInsertBrands(string batchJson)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    List<Dictionary<string,object>> brands = batchJson.FromJson<List<Dictionary<string,object>>>();
                    foreach (Dictionary<string, object> brand in brands)
                    {
                        using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                        {
                            cmd.CommandText = "proc_insert_new_brand";
                            cmd.Transaction = trans;
                            cmd.Parameters.Add("@code", SqlDbType.NVarChar).Value = brand["code"].ToString().ToUpper();
                            cmd.Parameters.Add("@level", SqlDbType.Float).Value = brand["level"].toFloat().Value;
                            cmd.Parameters.Add("@title", SqlDbType.VarChar).Value = brand["title"].ToString();
                            cmd.Parameters.Add("@title_origin", SqlDbType.VarChar).Value = brand["title_origin"].ToString();
                            cmd.Parameters.Add("@location", SqlDbType.VarChar).Value = brand["location"].ToString();
                            cmd.Parameters.Add("@desc", SqlDbType.VarChar).Value = brand["desc"].ToString();
                            cmd.ExecuteNonQuery();
                        }
                    }
                    try
                    {
                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string BatchInsertCatalogs(string batchJson)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    List<Dictionary<string, object>> catalogs = batchJson.FromJson<List<Dictionary<string, object>>>();
                    foreach (Dictionary<string, object> catalog in catalogs)
                    {
                        using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                        {
                            cmd.CommandText = "proc_insert_new_catalog";
                            cmd.Transaction = trans;
                            cmd.Parameters.Add("@ID", SqlDbType.Int).Value = catalog["ID"] == null ? (object)DBNull.Value : int.Parse(catalog["ID"].ToString());
                            cmd.Parameters.Add("@code", SqlDbType.NVarChar).Value = catalog["code"].ToString().ToUpper();
                            cmd.Parameters.Add("@title", SqlDbType.VarChar).Value = catalog["title"].ToString();
                            cmd.Parameters.Add("@title_en", SqlDbType.VarChar).Value = catalog["title_en"].ToString();
                            cmd.Parameters.Add("@parent_code", SqlDbType.VarChar).Value = string.IsNullOrEmpty(catalog["parent_code"].ToString()) ? (object)DBNull.Value : catalog["parent_code"].ToString();
                            cmd.Parameters.Add("@layer_num", SqlDbType.VarChar).Value = int.Parse(catalog["layer"].ToString());
                            cmd.ExecuteNonQuery();
                        }
                    }
                    try
                    {
                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string NeedSync(SyncType type,string timeTag)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_need_sync";
                    cmd.Parameters.Add("@syncType", SqlDbType.Int).Value = type;
                    cmd.Parameters.Add("@remoteDataTimeTag", SqlDbType.DateTime).Value = timeTag.toDateTime().Value;
                    cmd.Parameters.Add("@return",SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                    try
                    {
                        cmd.ExecuteNonQuery();
                        response.userinfo = cmd.Parameters["@return"].Value;
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string DeleteBrand(int id)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_delete_brand";
                    cmd.Parameters.Add("@brand_id", SqlDbType.Int).Value = id;
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string DeleteCatalog(int id)
        {
            ZKResponse response = new ZKResponse();
            string connStr = SqlConnectionManager.GetConnStrFromConfig();
            using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                {
                    cmd.CommandText = "proc_delete_catalog";
                    cmd.Parameters.Add("@catalog_id", SqlDbType.Int).Value = id;
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        response.isProcessSuccess = false;
                        response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                        response.errMsg = ex.Message;
                    }
                }
            }
            return response.ToJson();
        }
    }
}
